# container常用函数库

def getEnvList(data):
    """
    获取多个环境变量
    截取字符串
    :param string: 要截取的字符串
    :param filter: 截取规则
    :return dict
    """
    result = []
    if data is None:
        return None
    if data is not None:
        for value in data:
            print(value)
            if value is None:
                continue
            if value['key'] is not None and value['value'] is not None:
                result.append(value['key'] + '=' + value['value'])

    return result if len(result) > 0 else None


def getPortGroup(port):
    """
    获取port端口
    :param port: 端口列表
    :return:dict
    """
    result = {}
    if port is not None:
        # 获取端口映射
        for item in port:
            if len(item) is 0:
                continue
            elif item['export'] is not '' and item['port'] is not '':
                result[item['port']] = item['export']
    else:
        return None
    return result if len(result) > 0 else None


def getInputContainerNetwork(data):
    """
    获取network配置
    :return:
    """
    if data is None:
        return None
    result = {}
    result['hostname'] = data['hostname']
    result['network_mode'] = data['network_mode']
    result['mac_address'] = data['mac_address']

    return result


def assignIP(container, **kwargs):
    """
    链接上网络
    创建container 后调用
    :param data:
    :return:
    """
    from plugin.dk.Network import NetWork
    network = NetWork()
    print(kwargs)
    return network.connect(container['HostConfig']['NetworkMode'], container['Id'], **kwargs)


def getNetWorkIPConfig(data):
    """
    获取ip相关设置
    :param data:
    :return:
    """
    result = {}
    if data is None:
        return None
    result['ipv4_address'] = data['ipv4_address']
    for keys in result:
        if result[keys] is None:
            result.pop(keys)
    return result
